import React from 'react'

interface AdvantageChartProps {
  title: string
  data: number[]
  height?: number
  className?: string
}

// 简易SVG折线图，用于展示每分钟的优势曲线（经济或经验）
export default function AdvantageChart({ title, data, height = 220, className }: AdvantageChartProps) {
  const H = height
  const W = Math.max(100, (data?.length ?? 0)) // 使用数据点数量作为viewBox宽度，确保横向拉伸

  const pointsCount = data?.length ?? 0
  const maxAbs = pointsCount > 0 ? Math.max(...data.map(v => Math.abs(v))) || 1 : 1

  const zeroY = H / 2
  const paddingY = H * 0.08
  const scaleY = (H / 2 - paddingY) / maxAbs

  const path = React.useMemo(() => {
    if (!data || data.length === 0) return ''
    const cmds: string[] = []
    for (let i = 0; i < data.length; i++) {
      const x = i
      const y = zeroY - data[i] * scaleY
      cmds.push(i === 0 ? `M ${x} ${y}` : `L ${x} ${y}`)
    }
    return cmds.join(' ')
  }, [data, scaleY, zeroY])

  const zeroLine = `M 0 ${zeroY} L ${W} ${zeroY}`

  return (
    <div className={className}>
      <div className="flex items-center justify-between mb-2">
        <div className="text-sm font-medium">{title}</div>
        {pointsCount > 0 && (
          <div className="text-xs text-muted-foreground">时长: {pointsCount} 分钟 • 最大绝对值: {maxAbs}</div>
        )}
      </div>
      {pointsCount === 0 ? (
        <div className="text-sm text-muted-foreground">暂无数据</div>
      ) : (
        <svg
          viewBox={`0 0 ${W} ${H}`}
          preserveAspectRatio="none"
          className="w-full"
          style={{ height }}
        >
          {/* 背景网格（简化） */}
          <rect x={0} y={0} width={W} height={H} fill="transparent" />
          {/* 中线（零优势） */}
          <path d={zeroLine} stroke="#9ca3af" strokeDasharray="4 4" strokeWidth={0.8} />
          {/* 折线 */}
          <path d={path} fill="none" stroke="#3b82f6" strokeWidth={2} />
        </svg>
      )}
      <div className="mt-1 text-xs text-muted-foreground">数值`{'>'}`0 表示天辉领先，数值`{'<s'}`0 表示夜魇领先</div>
    </div>
  )
}